import { SVG, registerWindow } from '@svgdotjs/svg.js';
import { createSVGWindow } from 'svgdom';
import fs from 'fs';
import xml2js from 'xml2js';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

const window = createSVGWindow();
const document = window.document;
registerWindow(window, document);

const parseColor = (colorStr) => {
  if (!colorStr) {
    return 'rgb(255, 255, 255)'; // 默认返回白色
  }
  if (colorStr.startsWith('#')) {
    return colorStr;
  }
  return `rgb(${colorStr.split(',').map(Number).join(',')})`;
};

const createSVGElement = (element, svg) => {
  const type = element.name;
  const attrs = element.$;

  const fillColor = parseColor(attrs.fc || '#ffffff');
  const strokeColor = parseColor(attrs.lc || '#000000');
  const strokeWidth = parseInt(attrs.lw, 10) || 1;

  switch (type) {
    case 'circle':
      return svg.circle(parseInt(attrs.r, 10) * 2)
        .center(parseInt(attrs.cx, 10), parseInt(attrs.cy, 10))
        .fill(fillColor)
        .stroke({ color: strokeColor, width: strokeWidth });

    case 'Text':
      return svg.text(attrs.ts)
        .move(parseInt(attrs.x, 10), parseInt(attrs.y, 10))
        .font({
          size: parseInt(attrs.fs, 10),
          family: attrs.ff || 'Simsun',
          fill: fillColor
        })
        .stroke({ color: strokeColor, width: strokeWidth });

    case 'line':
      return svg.line(parseInt(attrs.x1, 10), parseInt(attrs.y1, 10), parseInt(attrs.x2, 10), parseInt(attrs.y2, 10))
        .stroke({ color: strokeColor, width: strokeWidth });

    case 'pin':
      return svg.circle(parseInt(attrs.r, 10) * 2)
        .center(parseInt(attrs.cx, 10), parseInt(attrs.cy, 10))
        .fill(fillColor)
        .stroke({ color: strokeColor, width: strokeWidth });

    default:
      console.warn(`Unknown element type: ${type}`);
      return null;
  }
};

const processLayer = (layerElement, svg) => {
  Object.keys(layerElement).forEach(key => {
    const elements = layerElement[key];
    if (Array.isArray(elements)) {
      elements.forEach(element => {
        const svgElement = createSVGElement({ name: key, $: element.$ }, svg);
        if (svgElement) {
          svg.add(svgElement);
        }
      });
    } else {
      console.warn(`Skipping non-array element: ${key}`);
    }
  });
};

const processElements = (elements, svg) => {
  elements.forEach(element => {
    const group = svg.group();
    if (element.Layer) {
      element.Layer.forEach(layer => processLayer(layer, group));
    }
  });
};

const convertXMLToSVG = (inputFile, outputFile) => {
  fs.readFile(inputFile, 'utf8', (err, data) => {
    if (err) {
      console.error(`Error reading file: ${err}`);
      return;
    }

    xml2js.parseString(data, (err, result) => {
      if (err) {
        console.error(`Error parsing XML: ${err}`);
        return;
      }

      const elements = [];
      Object.keys(result.G).forEach(key => {
        if (Array.isArray(result.G[key])) {
          elements.push(...result.G[key]);
        } else {
          console.warn(`Skipping non-array element: ${key}`);
        }
      });

      if (elements.length === 0) {
        console.error('No valid elements found');
        return;
      }

      const svg = SVG(document.documentElement).size(1000, 1000); // 设置一个默认的画布大小
      processElements(elements, svg);

      // 获取边界框，并设置viewBox
      const bbox = svg.bbox();
      svg.viewbox(bbox.x, bbox.y, bbox.width, bbox.height);

      fs.writeFile(outputFile, svg.svg(), (err) => {
        if (err) {
          console.error(`Error writing SVG file: ${err}`);
          return;
        }
        console.log(`SVG file saved to ${outputFile}`);
      });
    });
  });
};

// 设置输入和输出文件路径
const inputFile = 'symbols/PD_TXKG.txkg.icn.g'
const outputFile = path.join(__dirname, 'svgs');

// 执行转换
convertXMLToSVG(inputFile, outputFile);